import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Input, Radio, Block, Picker, Navigator, Button} from '@tarojs/components'
import './check-ticket.scss'
import {AtIcon, AtInputNumber, AtModalContent, AtModalAction, AtModal, AtTabs} from 'taro-ui'
import {user} from '../../utils/user.service'
import {http} from '../../utils/http'
import Index from "../components/water-mark/index";
import {
  NEW_TICKET_LIST,
  CHECK_TICKET,
  IDENTITY, DELIVERYPREPARE, CHECK_TICKET_BATCH
} from '../../constants/api'
import {UserIdentity} from '../../utils/server.interface'
import {GetRequest, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import NumberInput from "../components/number-input/number-input";
import {lxH5Wx} from "../../utils/lx.h5.service";

interface CheckList {
  product_name: string
  order_num: number
  check?: boolean
  order_id?: number
  pid: number
  id: number
  ticket_list: TicketList[]
}

interface TicketList {
  valid_date_start: string
  msg: string
  check?: boolean
  ticket: string
  check_num?: number
  can_check_num?: number
  used_check_num?: number
  valid_date_end: string
  goods?: any
  id: number
  is_use: number
  code_type: number
}

interface FormData {
  t: string
  check_num: number
  name?: string
}

export default class CheckTicket extends Component {
  type = 0; // 0 手动录入手机号或核验码    1 扫码进入的核验码
  state: {
    changeNum: boolean
    editNumber: number
    oldChangeNum: number
    checkedList: string[]
    supplierChecked: string
    checkList: CheckList[]
    inputText: string
    scanCode: string
    checkhas: boolean
    selectAll: boolean
    formData: FormData[]
    supplierList: any
    supplierIndex: number
    checkMsg: string
    orderNum: any
    codeParams: any
    current: any
  } = {
    orderNum: '',
    current: 0,
    codeParams: {},
    editNumber: 1,
    oldChangeNum: 1,
    changeNum: false,
    supplierList: [],
    supplierChecked: '',
    checkMsg: '',
    supplierIndex: 0,
    checkedList: [],
    checkList: [],
    inputText: '',
    checkhas: false,
    selectAll: false,
    formData: [],
    scanCode: '',
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    if (process.env.TARO_ENV === "weapp") {
      Taro.hideShareMenu()
    }
    const scanCode = Taro.getCurrentInstance().router.params.scene as string | undefined;
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    } else {
      const userIdentity = await http.get<UserIdentity>(IDENTITY, {})
      if (userIdentity && userIdentity.isSupplier) {
        const that = this
        let supplierChecked = ''
        let supplierIndex = Taro.getStorageSync('supplierIndex') || 0
        if (userIdentity.SupplierList.length > 0) {
          supplierIndex = userIdentity.SupplierList.length < supplierIndex ? userIdentity.SupplierList.length - 1 : supplierIndex
          supplierChecked = userIdentity.SupplierList[supplierIndex].company
          Taro.setStorageSync('supplierIndex', supplierIndex)
        }
        this.setState({scanCode, supplierList: userIdentity.SupplierList, supplierChecked, supplierIndex}, async () => {
          if (scanCode) {
            const checkList = await this.scanCodeGetData(scanCode)
            this.setState({checkList})
          }
          that.checkQuery()
        })
      } else {
        Taro.showToast({
          title: '您还不是核验员，请确认用户身份',
          icon: 'none',
          mask: true
        })
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/index/index'})
        }, 1500)
        return
      }
    }
  }

  async getData(keywords: string) {
    const {supplierList, supplierIndex, current, orderNum} = this.state
    const supplierId = supplierList[supplierIndex].supplier_id || 0
    const ret = await http.HGet(NEW_TICKET_LIST, {supplierId, keywords, verificationByDy: current, orderNum})
    if (ret) {
      ret.data.map(item => {
        item.check = false;
        item.ticket_list.map(v => {
          if (item.goods_group && item.goods_group === '团队预约') {
            v.check_num = v.custom_num
          } else {
            v.check_num = v.can_check_num > 0 ? 1 : 0
          }
          v.check = false
        })
      })
      if (ret.msg) {
        this.setState({
          checkMsg: ret.msg
        })
      }
      return ret.data;
    } else {
      return false;
    }
  }

  handleChange(status, i, index) {
    const {checkList} = this.state;
    const that = this
    checkList[i].ticket_list[index].check = !status
    that.setState({checkList}, () => {
      that.checkQuery()
    })
  }

  selectAll(item, i) {
    const {checkList} = this.state
    const that = this
    const check = !checkList[i].check;
    item.check = check;
    item.ticket_list.map(v => {
      v.check = check;
    })
    checkList[i] = item
    that.setState({checkList}, () => {
      that.checkQuery()
    })
  }

  inputEvent(i, index, e) {
    this.changeNum(i, index, e.detail.value)
  }

  changeNum(i, index, value) {
    const {checkList} = this.state
    const that = this
    checkList[i].ticket_list[index].check_num = value
    that.setState({checkList})
  }

  checkQuery() {
    const {checkList} = this.state
    const formData = []
    for (const item of checkList) {
      for (const val of item.ticket_list) {
        if (val.check) {
          formData.push({
            t: val.ticket,
            check_num: val.check_num,
            name: val.goods ? val.goods.goods_name : ''
          })
        }
      }
    }
    if (formData.length > 0) {
      this.setState({checkhas: true})
    } else {
      this.setState({checkhas: false})
    }
  }

  doCheck() {
    const {supplierList, supplierIndex, checkList} = this.state
    const supplierId = supplierList[supplierIndex].supplier_id
    const formData = []
    for (const item of checkList) {
      for (const val of item.ticket_list) {
        if (val.check) {
          formData.push({
            ext_keywords: item.goods_group === '团队预约' ? '团队预约' : '',
            t: val.ticket,
            check_num: val.check_num,
            name: val.goods ? val.goods.goods_name : ''
          })
        }
      }
    }
    if (!formData || formData.length <= 0) {
      Taro.showToast({
        title: '请选择要核销的数据!',
        icon: 'none'
      })
      return false
    }
    const that = this
    Taro.showModal({
      title: '提示',
      content: '验证码核销后无法撤销，确认核销当前选择的验证码？',
      success: async (res) => {
        if (res.confirm) {
          const retarr = []
          const errarr = []
          Taro.showLoading({
            title: '核销中'
          })
          if (!formData || formData.length <= 0) {
            Taro.showToast({
              title: '请选择要核销的数据!',
              icon: 'none'
            })
            Taro.hideLoading()
            return false
          }
          if (JSON.stringify(that.state.codeParams) !== '{}') { // 扫码的抖音核销
            const array = []
            formData.map(item => array.push(item.t))
            const ret = await http.HPost(CHECK_TICKET_BATCH, { num: 1, verificationByDy: 1, newKeywords: array.join(','), supplierId }, true)
            Taro.showModal({
              title: '核销提示',
              content: ret.message || ret.msg || ret.data.msg || ret.data.message,
              showCancel: false,
              success: async (res) => {
                if (res.confirm) {
                  await that.showModelTips()
                }
              }
            })
            Taro.hideLoading()
          } else {
            for (const i in formData) {
              const data = {
                ext_keywords: formData[i].ext_keywords,
                supplierId,
                keywords: formData[i].t,
                num: formData[i].check_num,
                verification_srouce: 0
              }
              const ret = await http.HPost(CHECK_TICKET, data, true)
              if (ret.data) {
                retarr.push(ret.data)
              } else {
                errarr.push(ret.msg || ret.message)
              }
            }
            Taro.hideLoading()
            Taro.showModal({
              title: '核销提示',
              content: retarr.length == formData.length ? '核销成功' : errarr.join('|'),
              showCancel: false,
              success: async (res) => {
                if (res.confirm) {
                  await that.showModelTips()
                }
              }
            })
          }
        }
      }
    })
  }

  async showModelTips() {
    if (this.type === 0) {
      Taro.showLoading({title: '刷新中...'})
      const checkList = await this.getData(this.state.inputText)
      this.setState({checkList}, () => {
        this.checkQuery()
      })
      const timer = setTimeout(() => {  // 解决微信hideLoading不生效bug
        Taro.hideLoading()
        clearTimeout(timer)
      }, 100)
    } else {
      Taro.showLoading({title: '刷新中...'})
      const checkList = await this.scanCodeGetData(this.state.scanCode)
      this.setState({checkList}, () => {
        this.checkQuery()
      })
      const timer = setTimeout(() => {  // 解决微信hideLoading不生效bug
        Taro.hideLoading()
        clearTimeout(timer)
      }, 100)
    }
  }

  async scan() {
    const {supplierIndex} = this.state
    if (supplierIndex < 0) {
      Taro.showToast({
        title: '请先选择供应商',
        icon: 'none'
      })
      return
    }
    this.type = 1
    if (process.env.TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        lxH5Wx.scanCode(result => {
          this.handlerScan(result)
        })
      } else {
        h5Wx.scanQRCode(async res => {
          this.handlerScan(res.resultStr)
        })
      }
      return
    } else {
      const ret = await Taro.scanCode({onlyFromCamera: true})
      Taro.showLoading({title: '识别中...'})
      let scanCode = ''
      const params = {}
      if (ret.scanType == 'WX_CODE') {
        scanCode = ret.path.split("=")[1]
      } else {
        scanCode = ret.result
      }
      if (scanCode && scanCode.indexOf('scene=') != -1) {
        scanCode = scanCode.split('scene=')[1]
      } else if (scanCode.includes('encrypted_data')){
        const code = scanCode.split('?')[1].split('&');
        code.map(item => {
          const result = item.split('=')
          params[result[0]] = result[1]
        })
        const {supplierList, supplierIndex} = this.state
        params.supplier_id = supplierList[supplierIndex].supplier_id
        const res = await http.HPost(DELIVERYPREPARE, params)
        if (res && res.data && res.data.keywords) {
          scanCode = res.data.keywords
        }
      }
      this.setState({scanCode: scanCode || '', codeParams: params}, async () => {
        const list = await this.scanCodeGetData(scanCode)
        list.map(item => {
          item.check = false;
          item.ticket_list.map(v => {
            if (item.goods_group && item.goods_group === '团队预约') {
              v.check_num = v.custom_num
            } else {
              v.check_num = v.can_check_num > 0 ? 1 : 0
            }
            v.check = false
          })
        })
        Taro.hideLoading()
        if (list) {
          this.setState({checkList: list || []})
        } else {
          Taro.showToast({title: '未找到验证码信息', icon: 'none'})
        }
      })
    }

    const timer = setTimeout(() => {  // 解决微信hideLoading不生效bug
      Taro.hideLoading()
      clearTimeout(timer)
    }, 100)
  }

  handlerScan(resultStr){
    setTimeout(async () => {
      Taro.showLoading({title: '识别中...'})
      let scanCode = resultStr
      const params = {}
      if (scanCode && scanCode.indexOf('scene=') != -1) {
        scanCode = scanCode.split('scene=')[1]
      } else if (scanCode.includes('encrypted_data')){
        const code = scanCode.split('?')[1].split('&');
        code.map(item => {
          const result = item.split('=')
          params[result[0]] = result[1]
        })
        const {supplierList, supplierIndex} = this.state
        params.supplier_id = supplierList[supplierIndex].supplier_id
        const res = await http.HPost(DELIVERYPREPARE, params)
        if (res && res.data && res.data.keywords) {
          scanCode = res.data.keywords
        }
      }
      this.setState({scanCode: scanCode || '', codeParams: params}, async () => {
        const list = await this.scanCodeGetData(scanCode)
        list.map(item => {
          item.check = false;
          item.ticket_list.map(v => {
            if (item.goods_group && item.goods_group === '团队预约') {
              v.check_num = v.custom_num
            } else {
              v.check_num = v.can_check_num > 0 ? 1 : 0
            }
            v.check = false
          })
        })
        Taro.hideLoading()
        if (list) {
          this.setState({checkList: list || []})
        } else {
          Taro.showToast({title: '未找到验证码信息', icon: 'none'})
        }

      })
    }, 2000)
  }

  onChange(e) {
    const {supplierList} = this.state
    const supplierIndex = Number(e.detail.value)
    const supplierChecked = supplierList[supplierIndex].company
    this.setState({supplierIndex, supplierChecked}, () => {
      Taro.setStorageSync('supplierIndex', supplierIndex)
    })
  }

  async scanCodeGetData(keywords: string) {
    const {supplierList, supplierIndex} = this.state
    const supplierId = supplierList[supplierIndex].supplier_id
    if (!supplierId) {
      Taro.showToast({
        title: '请选择所属供应商',
        icon: 'none'
      })
      return
    }
    const ret = await http.HGet(NEW_TICKET_LIST, {supplierId, keywords})
    if (ret) {
      ret.data.map(item => {
        item.check = false;
        item.ticket_list.map(v => {
          v.check_num = v.can_check_num > 0 ? 1 : 0
          v.check = false
        })
      })
      if (ret.msg) {
        this.setState({
          checkMsg: ret.msg
        })
      }
      return ret.data;
    } else {
      return false;
    }
  }

  inputChange(value) {
    this.setState({inputText: value.detail.value.trim()})
  }

  inputChangeOrderNum(value) {
    this.setState({orderNum: value.detail.value.trim()})
  }

  submiting = false

  async submit() {
    this.setState({ codeParams: {} })
    const {supplierIndex, inputText} = this.state
    if (supplierIndex < 0) {
      Taro.showToast({
        title: '请先选择供应商',
        icon: 'none'
      })
      return
    }
    this.type = 0
    if (this.submiting) {
      Taro.showToast({title: '亲，稍安勿躁~', icon: 'none'})
      return
    }
    this.submiting = true
    if (inputText) {
      Taro.showLoading({title: '加载中...'})
      const checkList = await this.getData(inputText)
      if (checkList) {
        if (checkList) {
          this.setState({checkList}, () => {
            Taro.hideLoading()
          })
        } else {
          Taro.showToast({title: '未找到验证码信息', icon: 'none'})
        }
      } else {
        Taro.hideLoading()
      }
    } else {
      Taro.showToast({title: '请先输入核验信息', icon: 'none'})
    }
    this.submiting = false
  }

  onCopy(str, e) {
    e.stopPropagation()
    try {
      Taro.setClipboardData({
        data: str
      })
      if (process.env.TARO_ENV === 'h5') {
        Taro.showToast({title: '复制成功'})
      }
    } catch (e) {
      Taro.showToast({title: '复制失败'})
    }
  }

  onShowImg(current, e) {
    e.stopPropagation()
    Taro.previewImage({
      current, // 当前显示图片的http链接
      urls: [current] // 需要预览的图片http链接列表
    })
  }

  async inputNumber() {

  }

  handlerSelectAll() {
    let {selectAll} = this.state
    selectAll = !selectAll
    this.setState({selectAll})
    const {checkList} = this.state
    const that = this
    checkList.map((item) => {
      item.check = selectAll
      item.ticket_list.map(v => {
        v.check = selectAll
      })
    })
    that.setState({checkList}, () => {
      that.checkQuery()
    })
  }

  confirmChangeNum() {

  }

  handleClick (value) {
    this.setState({
      current: value
    })
  }

  tabList = [{ title: '核销' }, { title: '抖音核销' }]

  render() {
    const {
      oldChangeNum,
      changeNum,
      editNumber,
      selectAll,
      checkList,
      inputText,
      checkhas,
      supplierList,
      supplierChecked,
      supplierIndex,
      current,
      checkMsg
    } = this.state
    return (
      <View className='check-ticket-root'>
        <GzhAuth />
        <Index />
        <AtTabs current={current} tabList={this.tabList} onClick={this.handleClick.bind(this)}>
        </AtTabs>
        <View className='head-bg'>
          <View className='header-bar'>
            <View className='head-picker'>
              {supplierList.length > 0 && <Picker value={supplierIndex} range={supplierList} rangeKey='company'
                onChange={this.onChange.bind(this)}
              >
                <View className={supplierChecked ? 'picker' : 'picker off'}>
                  {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                  {supplierList.length > 1 && <Text>切换</Text>}
                </View>
              </Picker>}
            </View>
          </View>
          <View className='input-box'>
            <View className='scan' onClick={this.scan.bind(this)}>
              <AtIcon prefixClass='xxhz' value='saoma' size='22' color='black' />
            </View>
            <View className='input'>
              <Input className={`${process.env.TARO_ENV}`} value={inputText} placeholderClass='input_pla'
                placeholder='手机号/验证码核销'
                onInput={this.inputChange.bind(this)}
              />
            </View>
            <View className='btn' onClick={this.submit.bind(this)}><AtIcon prefixClass='xxhz' value='sousuo2' size='18'
              color='#fff'
            /></View>
          </View>
        </View>
        <View className='content'>
          {checkList.length > 1 && <View className='select-all'>
            <Radio checked={selectAll} color='#fe9f00' />
            <Text onClick={() => this.handlerSelectAll()} className='allText'>全选</Text>
          </View>}
          {checkList.length > 0 && checkList.map((item: any, i) => <View className='card' key={item.id}>
            <View className='card-title'>
              <Radio checked={item.check} color='#fe9f00' value={item.id} />
              <View className='text allText'
                onClick={() => this.selectAll(item, i)}
              >{(item.goods_list && item.goods_list.length > 0 && item.goods_list[0].alias) ? item.goods_list[0].alias :item.product_name }{item.goods_group &&
                <Text>- {item.goods_group}</Text>}</View>
            </View>
            <View className='card-content'>
              {item.ticket_list.length > 0 && item.ticket_list.map((val: any, index) =>
                <View className='card-content-item' key={index}>
                  <View className='card-content-left'>
                    <Radio checked={val.check} color='#fe9f00' value={val.id} />
                    <Text className='allText' onClick={() => this.handleChange(val.check, i, index)} />
                  </View>
                  <View className='card-content-right'>
                    {!item.goods_group && <View className='name'><Text className='allText'
                      onClick={this.handleChange.bind(this, val.check, i, index)}
                    >{(val.goods && val.goods.alias) ? val.goods.alias: val.goods.goods_name}</Text>
                      <Navigator url={'/main/supplier/order-ticket?id=' + item.order_id} hoverClass='none'><AtIcon
                        value='chevron-right' size='15' color='#ddd'
                      /></Navigator></View>}
                    {val.is_use > 1 && val.is_use < 5 ?
                      <View className='ticket hui'>
                        <View className='break-word'>
                          {val.code_type == 2 &&
                            <Image src={val.ticket} onClick={this.onShowImg.bind(this, val.ticket)} mode='aspectFill' />}
                          {val.code_type == 3 ? <View className='break-word-box'
                            onClick={this.onCopy.bind(this, val.ticket)}
                          >{val.ticket} {val.msg}
                              <Text className='ticket_copy'
                                onClick={this.onCopy.bind(this, val.ticket)}
                              >[复制]</Text></View> :
                            <Block>{val.code_type != 2 &&
                              <View className='break-word-box'>{val.ticket} {val.msg}</View>}</Block>}
                        </View>
                        {item.goods_group && item.goods_group === '团队预约' && <View className='float-right'>
                          到场人数：<NumberInput val={val.check_num} index={index} step={1} min={0}
                            thisChange={this.changeNum.bind(this, i, index)}
                          />
                        </View>}
                        {(!item.goods_group && val.is_use === 2) && <View className='float-right'>已失效<Text>{val.can_check_num
                        }</Text></View>}
                        {(!item.goods_group && val.is_use === 4) && <View className='float-right'>已过期<Text>{val.can_check_num}</Text></View>}
                      </View>
                      :
                      <Block>
                        <View className='ticket'>
                          <View className='break-word'>{val.code_type == 2 &&
                            <Image src={val.ticket} onClick={this.onShowImg.bind(this, val.ticket)} mode='aspectFill' />}
                            {val.code_type == 3 ?
                              <View className='break-word-box'
                                onClick={this.onCopy.bind(this, val.ticket)}
                              >{val.ticket}
                                <Text className='ticket_copy'
                                  onClick={this.onCopy.bind(this, val.ticket)}
                                >[复制]</Text></View> :
                              <Block>{val.code_type != 2 &&
                                <View className='break-word-box'>{val.ticket}</View>}</Block>}
                          </View>
                          {item.goods_group && item.goods_group === '团队预约' && <View className='float-right'>
                            到场人数：<NumberInput val={val.check_num} index={index} step={1} min={0}
                              thisChange={this.changeNum.bind(this, i, index)}
                            />
                          </View>}
                          {!item.goods_group &&
                            <View className='float-right'>未核验<Text>{val.can_check_num}</Text></View>}
                          {!item.goods_group &&
                            <View className='float-right'>已核验<Text>{val.used_check_num}</Text></View>}
                        </View>
                        {val.can_check_num > 1 && <View className='ticket_num'>
                          <Text>请选择需核验的数量</Text>
                          <AtInputNumber
                            min={1}
                            max={val.can_check_num}
                            step={1}
                            value={val.check_num}
                            disabledInput
                            onChange={this.changeNum.bind(this, i, index)}
                          />
                        </View>}
                      </Block>
                    }
                  </View>
                </View>
              )}
            </View>
          </View>)}
          {checkList.length == 0 && checkMsg &&
            <View className='checkMsg'><View>抱歉,没有找到可以核验的码.可能的原因是</View><View>[{checkMsg}]</View></View>}
        </View>
        {checkhas && <View className='submit' onClick={this.doCheck.bind(this)}>
          核销
        </View>}
        {changeNum && <AtModal isOpened={changeNum} className='changeNum'>
          <AtModalContent>
            <View>原预约人数：{oldChangeNum}</View>
            <View>更改后预约人数：<AtInputNumber
              min={1}
              max={10}
              type='number'
              step={1}
              value={editNumber}
              onChange={this.handleChange.bind(this)}
            /></View>
          </AtModalContent>
          <AtModalAction><Button onClick={() => {
            this.setState({changeNum: false})
          }}
          >取消</Button><Button onClick={this.confirmChangeNum.bind(this)}>确定</Button></AtModalAction>
        </AtModal>}
      </View>
    )
  }
}
